<template>
  <div style="width: 100%;margin-top: 1rem">
    <a-row>
      <a-col :span="7">
        <a-form-item
          label="Redis节点"
          style="border-bottom: 5px #f1f1f1;"
          :labelCol="{ span: 6 }"
          :wrapperCol="{ span: 15, offset: 0 }"
        >
          <a-select
            mode="simple"
            :allowClear="false"
            v-model="node"
            @change="handleNodeChange"
            style="width: 100%"
          >
            <a-select-option v-for="value in redisNodes" :key="value">{{
              value
            }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="8">
      <a-col :span="12">
        <apexchart
          ref="memoryInfo"
          type="area"
          height="350"
          :options="memory.chartOptions"
          :series="memory.series"
        />
      </a-col>
      <a-col :span="12">
        <apexchart
          ref="keySize"
          type="area"
          height="350"
          :options="key.chartOptions"
          :series="key.series"
        />
      </a-col>
    </a-row>
    <a-row
      :gutter="8"
      v-for="(sortedInfo, sortedIndex) in sortedRedisInfo"
      :key="sortedIndex"
    >
      <!--遍历sortedRedisInfo-->
      <a-divider orientation="left"
        ><p style="color:black">{{ sortedInfo.topic }}</p></a-divider
      >
      <table style="border-bottom: 1px solid #f1f1f1; width: 100%">
        <tr
          v-for="(info, index) in sortedInfo.infoList"
          :key="index"
          style="border-top: 1px solid #f1f1f1;"
        >
          <td style="padding: .7rem 1rem; width: 20%">{{ info.key }}</td>
          <td style="padding: .7rem 1rem; width: 55%">
            {{ info.description }}
          </td>
          <td style="padding: .7rem 1rem; width: 25%">{{ info.value }}</td>
        </tr>
      </table>
    </a-row>
  </div>
</template>
<script>
import axios from "axios";
import moment from "moment";

export default {
  name: "RedisInfo",
  data() {
    return {
      loading: true,
      redisNodes: [],
      node: "",
      memory: {
        series: [],
        chartOptions: {
          chart: {
            animations: {
              enabled: true,
              easing: "linear",
              dynamicAnimation: {
                speed: 3000
              }
            },
            toolbar: {
              show: false
            },
            zoom: {
              enabled: false
            }
          },
          dataLabels: {
            enabled: false
          },
          stroke: {
            curve: "smooth"
          },
          title: {
            text: "Redis内存实时占用情况（kb）",
            align: "left"
          },
          markers: {
            size: 0
          },
          xaxis: {},
          yaxis: {},
          legend: {
            show: false
          }
        },
        data: [],
        xdata: []
      },
      key: {
        series: [],
        chartOptions: {
          chart: {
            animations: {
              enabled: true,
              easing: "linear",
              dynamicAnimation: {
                speed: 3000
              }
            },
            toolbar: {
              show: false
            },
            zoom: {
              enabled: false
            }
          },
          dataLabels: {
            enabled: false
          },
          colors: ["#f5564e"],
          stroke: {
            curve: "smooth"
          },
          title: {
            text: "Redis key实时数量（个）",
            align: "left"
          },
          markers: {
            size: 0
          },
          xaxis: {},
          yaxis: {},
          legend: {
            show: false
          }
        },
        data: [],
        xdata: []
      },
      sortedRedisInfo: [],
      timer: null
    };
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  mounted() {
    this.loadRedisNodes();
    let minMemory = 1e10;
    let minSize = 1e10;
    let maxMemory = -1e10;
    let maxSize = -1e10;
    this.timer = setInterval(() => {
      if (this.$route.path.indexOf("redis") !== -1) {
        axios
          .all([
            this.$get("api/redis/keysSize", { node: this.node }),
            this.$get("api/redis/memoryInfo", { node: this.node })
          ])
          .then(r => {
            let currentMemory = r[1].data.data.used_memory / 1000;
            let currentSize = r[0].data.data.dbSize;
            if (currentMemory < minMemory) {
              minMemory = currentMemory;
            }
            if (currentMemory > maxMemory) {
              maxMemory = currentMemory;
            }
            if (currentSize < minSize) {
              minSize = currentSize;
            }
            if (currentSize > maxSize) {
              maxSize = currentSize;
            }
            let time = moment().format("hh:mm:ss");
            this.memory.data.push(currentMemory);
            this.memory.xdata.push(time);
            this.key.data.push(currentSize);
            this.key.xdata.push(time);
            if (this.memory.data.length >= 6) {
              this.memory.data.shift();
              this.memory.xdata.shift();
            }
            if (this.key.data.length >= 6) {
              this.key.data.shift();
              this.key.xdata.shift();
            }
            this.$refs.memoryInfo.updateSeries([
              {
                name: "内存(kb)",
                data: this.memory.data.slice()
              }
            ]);
            this.$refs.memoryInfo.updateOptions(
              {
                xaxis: {
                  categories: this.memory.xdata.slice()
                },
                yaxis: {
                  min: minMemory,
                  max: maxMemory
                }
              },
              true,
              true
            );
            this.$refs.keySize.updateSeries([
              {
                name: "key数量",
                data: this.key.data.slice()
              }
            ]);
            this.$refs.keySize.updateOptions(
              {
                xaxis: {
                  categories: this.key.xdata.slice()
                },
                yaxis: {
                  min: minSize - 2,
                  max: maxSize + 2
                }
              },
              true,
              true
            );
            if (this.loading) {
              this.loading = false;
            }
          })
          .catch(r => {
            console.error(r);
            this.$message.error("获取Redis信息失败");
            if (this.timer) {
              clearInterval(this.timer);
            }
          });
      }
    }, 3000);
    this.getSortedRedisInfo();
  },
  methods: {
    loadRedisNodes() {
      this.$get("api/redis/nodes", {}).then(r => {
        this.redisNodes = r.data.data;
        this.node = this.redisNodes[0];
      });
    },
    getSortedRedisInfo() {
      this.$get("api/redis/info", { node: this.node }).then(r => {
        this.sortedRedisInfo = r.data.data;
      });
    },
    handleNodeChange() {
      this.memory.data = [];
      this.memory.xdata = [];
      this.key.data = [];
      this.key.xdata = [];
      this.sortedRedisInfo = [];
      this.getSortedRedisInfo();
    }
  }
};
</script>
<style></style>
